package com.v2future.sjt.collegecheckingattendance.personal;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.v2future.sjt.collegecheckingattendance.LazyFragment;
import com.v2future.sjt.collegecheckingattendance.LoginActivity;
import com.v2future.sjt.collegecheckingattendance.R;
import com.v2future.sjt.collegecheckingattendance.home.bean.LoginResultBean;
import com.v2future.sjt.collegecheckingattendance.utils.BaseResponseBean;
import com.v2future.sjt.collegecheckingattendance.utils.Constants;
import com.v2future.sjt.collegecheckingattendance.utils.PreferencesUtil;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.BaseRequestParams;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetTaskListener;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetUtils;

import org.xutils.x;

import java.io.File;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by minnie on 16/1/17.
 * 个人信息
 */
public class PersonalFragment extends LazyFragment implements View.OnClickListener{

    private TextView nameTv, collegeTv, collegeDetailTv;
    private LinearLayout userInfoLayout,collectLayout,messageLayout,configLayout;
    private Button exitBtn;
    private ImageView headIv;
    int REQUEST_IMAGE = 1001;
    String imagePath;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_personal, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        nameTv = (TextView) view.findViewById(R.id.tv_name);
        collegeTv = (TextView) view.findViewById(R.id.tv_college);
        collegeDetailTv = (TextView) view.findViewById(R.id.tv_college_detail);
        exitBtn = (Button) view.findViewById(R.id.btn_exit);
        headIv = (ImageView) view.findViewById(R.id.iv_icon);
        headIv.setOnClickListener(upLoadHeadListener);
        exitBtn.setOnClickListener(this);
        userInfoLayout = (LinearLayout) view.findViewById(R.id.layout_info);
        userInfoLayout.setOnClickListener(this);
        collectLayout = (LinearLayout) view.findViewById(R.id.layout_collect);
        collectLayout.setOnClickListener(this);
        messageLayout = (LinearLayout) view.findViewById(R.id.layout_message);
        messageLayout.setOnClickListener(this);
        configLayout = (LinearLayout) view.findViewById(R.id.layout_config);
        configLayout.setOnClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        String name = getBaseActivity().getUserInfo().getData().getUserName();
        if (!TextUtils.isEmpty(name)) {
            nameTv.setText(getBaseActivity().getUserInfo().getData().getUserName());
        }
        String college = getBaseActivity().getUserInfo().getData().getMajorName();
        String typeName = getBaseActivity().getUserInfo().getData().getSourceSecTypeName();
        if (!TextUtils.isEmpty(college)) {
            collegeTv.setText(college);
        }
        else if(!TextUtils.isEmpty(typeName)){
            collegeTv.setText(typeName);
        }
        String collegeDetail = getBaseActivity().getUserInfo().getData().getClassName();
        if (!TextUtils.isEmpty(collegeDetail)) {
            collegeDetailTv.setText(collegeDetail);
        }
        else {
            collegeDetailTv.setVisibility(View.GONE);
        }
        String headId = getBaseActivity().getUserInfo().getData().getPortraitNum();
        try {
            String headUrl = getBaseActivity().getUserInfo().getData().getUserPic();
            if (!TextUtils.isEmpty(headUrl)) {
                x.image().bind(headIv, headUrl, getBaseActivity().getCircleImageOptions(60, 60));
            }
            else {
                getBaseActivity().setDefaultHead(headIv);
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void lazyLoad() {

    }

    /**
     * 设置头像
     * @param path
     */
    public void setHead(List<String> path){
        if (path.size() > 0 ) {
            imagePath = path.get(0).toString();
            doUpLoadHead();
        }
        else {
            getBaseActivity().tip("头像图片选择错误");
        }
    }

    /**
     * 上传头像
     */
    private void doUpLoadHead(){
        BaseRequestParams params = new BaseRequestParams(getBaseActivity(), getBaseActivity().formatUrlDo(Constants.PUBLISH_EVENT));
        params.addQueryStringParameter("type", "1");
        params.setMultipart(true);
        params.addQueryStringParameter("imageName0", getBaseActivity().urlEncode(imagePath));
        params.addBodyParameter("imageBody0", new File(imagePath), null);
        NetUtils.doPostRequestWithFiles(getBaseActivity(), params, new NetTaskListener<BaseResponseBean>() {

            /**
             * 数据获取完成
             *
             * @param result
             */
            @Override
            public void onSuccess(BaseResponseBean result) {
                //获取用户信息，刷新头像
                doGetUserInfo();
                getBaseActivity().showOneBtnDialog(getString(R.string.notice), "上传头像完成", getString(R.string.iknow), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getBaseActivity().HideDialog();
                    }
                });
            }

            /**
             * 位置网络错误
             */
            @Override
            public void onError() {

            }

            /**
             * 非正常状态的数据
             *
             * @param result
             */
            @Override
            public void onInterError(BaseResponseBean result) {
                getBaseActivity().tip(result.getFailReason());
            }

            /**
             * 网络错误
             *
             * @param responseCode
             * @param responseMsg
             * @param errorResult
             */
            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {
                getBaseActivity().tip(responseMsg);
            }

            /**
             * 请求取消
             */
            @Override
            public void onCancelled() {

            }

            /**
             * 网络请求流程结束
             */
            @Override
            public void onFinished() {
                getBaseActivity().cancelLoadingDialog();
            }

            /**
             * 缓存获取完成
             *
             * @param result
             */
            @Override
            public void onSuccessCache(BaseResponseBean result) {

            }
        });
    }

    /**
     * 获取用户信息
     */
    public void doGetUserInfo(){
        BaseRequestParams params = new BaseRequestParams(getBaseActivity(), getBaseActivity().formatUrl(Constants.GET_USER_INFO));
        params.addQueryStringParameter("sourceTypeId",getBaseActivity().getUserInfo().getData().getSourceTypeId());
        NetUtils.doGetRequest(getBaseActivity(), params, new NetTaskListener<LoginResultBean>() {

            @Override
            public void onSuccess(LoginResultBean result) {
                if (null != result && !TextUtils.isEmpty(result.getData().getUserCode())) {
                    getBaseActivity().getBaseApplication().insertCathe(Constants.CACHE_KEY_USER_INFO, result);
                    String headId = getBaseActivity().getUserInfo().getData().getPortraitNum();
                    String headUrl = getBaseActivity().getUserInfo().getData().getUserPic();
                    if (!TextUtils.isEmpty(headUrl)) {
                        x.image().bind(headIv, headUrl, getBaseActivity().getCircleImageOptions(40, 40));
                    }
                    else {
                        getBaseActivity().setDefaultHead(headIv);
                    }
                }
            }

            @Override
            public void onError() {

            }

            @Override
            public void onInterError(LoginResultBean result) {

            }

            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {

            }

            @Override
            public void onCancelled() {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onSuccessCache(LoginResultBean result) {

            }
        });
    }

    /**
     * 上传头像界面跳转
     */
    private View.OnClickListener upLoadHeadListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getBaseActivity(), MultiImageSelectorActivity.class);
            // whether show camera
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
            // max select image amount
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
            // select mode (MultiImageSelectorActivity.MODE_SINGLE OR MultiImageSelectorActivity.MODE_MULTI)
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
            // default select images (support array list)
//                intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, defaultDataArray);
            getBaseActivity().startActivityForResult(intent, Constants.IMAGE_CODE);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_exit://注销
                getBaseActivity().getBaseApplication().removeCathe(Constants.CACHE_KEY_USER_INFO);//删除缓存的用户信息
                //重置保存的用户信息
                PreferencesUtil.setSharedStringData(getBaseActivity(), Constants.PREFERENCE_USERNAME, "");
                PreferencesUtil.setSharedStringData(getBaseActivity(), Constants.PREFERENCE_PWD, "");
                PreferencesUtil.setSharedStringData(getBaseActivity(), Constants.PREFERENCE_USER_TYPE, "");
                Intent loginIntent = new Intent(getBaseActivity(), LoginActivity.class);
                startActivity(loginIntent);
                getBaseActivity().finish();
                break;
            case R.id.layout_info://基本信息
                Intent basicInfoIntent = new Intent(getBaseActivity(), BasicInfoActivity.class);
                startActivity(basicInfoIntent);
                break;
            case R.id.layout_collect:

                break;
            case R.id.layout_message:

                break;
            case R.id.layout_config:
                Intent configIntent = new Intent(getBaseActivity(), SettingActivity.class);
                startActivity(configIntent);
                break;
            default:
                break;
        }
    }
}
